<template>
	<uni-popup ref="infoPopup" background-color="#fff">
		<view class="infoPopup-content">
			<view class="">
				请选择错题专题
			</view>
			<view class="item1" v-for="(item1,index1) in tableList" :key="index1">
				<view class="title" @click="goError(item1)">					
					<view class="section-name">
						{{item1.label}}
					</view>
				</view>
			
			</view>
		</view>
	</uni-popup>
	<view class="contentList">
		
		<view class="top">
			<view class="top-img">

			</view>
			<view class="top-text">

			</view>
		</view>
		
		<view class="body-top">
			<view class="img">
				<image src="../../static/book13.png" mode=""></image>
			</view>
			<view class="bookName">
				{{label}}
			</view>
			<view class="count">
				<text>共{{totalNum}}题 </text>
				<text> &nbsp;&nbsp;&nbsp;{{participants}}人参与</text>
			</view>
			<view class="rate">
				<view class="rate-num">
					{{correctNum == 0 ? 0 : (correctNum * 100 / doneNum).toFixed(0) }} %
				</view>
				<view class="rate-text">
					正确率
				</view>
			</view>

		</view>
		
		<view class="body">
			<view class="body-title">
				<view class="left" @click="redo">
					<view class="img">
						<image src="../../static/remake.png" mode=""></image>
					</view>
					<view class="text">
						重新刷题
					</view>
				</view>
				<view class="error" @click="errorPDF">
					<view class="img">
						<image src="../../static/export.png" mode=""></image>
					</view>
					<view class="text">
						错题导出
					</view>
				</view>
				<view class="middle" @click="goErrorList">
					<view class="img">
						<image src="../../static/order.png" mode=""></image>
					</view>
					<view class="text">
						错题集
					</view>
				</view>
				<view class="right" @click="gorandom">
					<view class="img">
						<image src="../../static/rand.png" mode=""></image>
					</view>
					<view class="text">
						随机测试
					</view>
				</view>
			</view>
			<view class="showType">
				<view :class="showType == 1 ? 'selected' : ''" @click="changeShowType(1)">
					内容
				</view>
				<view :class="showType == 2 ? 'selected' : ''" @click="changeShowType(2)">
					分析
				</view>
			</view>
			<view class="section" v-show="showType == 1">
				<view class="item1" v-for="(item1,index1) in tableList" :key="index1">
					<view class="title" @click="changeExpand(index1,item1)">
						<view class="section-icon">
							<image :src="determin(item1.expand)" mode=""></image>
						</view>
						<view class="section-name">
							{{item1.label}}
						</view>

						<view class="schedule">
							{{item1.total}}
						</view>
					</view>
					<view class="item2-box" v-show="item1.expand">
						<view class="item2" v-for="(item2,index2) in item1.children" :key="index2"
							@click="goQuestionList(item2)">
							<view class="chapterName">
								{{item2.label}}
							</view>
							<view class="rate">
								{{item2.done}} / {{item2.total}}
								<view class="item2-icon">
									<image src="../../static/more.png" mode=""></image>

								</view>
							</view>

						</view>
					</view>

				</view>
			</view>
			<view class="box" v-show="showType == 2">
				<JnChart canvasId="bar" :option="optionBar" lazyLoad />
			</view>
		</view>

	</view>
</template>

<script setup>
	import JnChart from '../../components/jn-chart/index.vue'
	import {
		ref
	} from 'vue'
	import {
		onShow,
		onLoad
	} from "@dcloudio/uni-app"
	import {
		useRoute
	} from "vue-router";
	import util from '../../util/index.js'
	// import PDFDocument from 'pdfkit'
	const optionBar = ref({})
	const totalNum = ref(0);
	const correctNum = ref(0);
	const doneNum = ref(0);
	const seriesId = ref('');
	const sectionId = ref('');
	const teacherId = ref('');
	const route = useRoute();
	const showType = ref(1)
	const tableList = ref([]);
	const label = ref('')
	const participants = ref('')
	const infoPopup = ref()
	onLoad((query) => {

		const ids = JSON.parse(query.ids)

		seriesId.value = ids.seriesId
		teacherId.value = ids.teacherId
		label.value = query.label
		participants.value = query.participants
		// getData()

	})
	onShow(() => {
		totalNum.value = 0;
		correctNum.value = 0;
		doneNum.value = 0;
		getSection(seriesId.value);
	})

	const changeShowType = (value) => {
		console.log('changeShowType', value)
		// showType.value = value
		if (value == 2) {
			const userInfo = uni.getStorageSync("userInfo");
			if (userInfo.vip != 2) {
				uni.showModal({
					title: '提示',
					content: '该功能为vip2特权功能，请升级',
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: "/pages/buy/buy",
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});

			} else {
				showType.value = value
				adjustEchartData(tableList.value)
			}

		} else {
			showType.value = value
		}

	}
	const errorPDF = () => {
		const userInfo = uni.getStorageSync("userInfo");
		if (userInfo.vip != 2) {
			uni.showModal({
				title: '提示',
				content: '该功能为vip2特权功能，请升级',
				success: function(res) {
					if (res.confirm) {
						uni.navigateTo({
							url: "/pages/buy/buy",
						});
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});

		} else {
			uni.showLoading({
				title: '下载中，请稍后'
			});

			uni.request({
				url: util.baseUrl + '/wxapi/wxQuestion/errorPDF',
				method: 'post',
				data: {
					userId: userInfo._id,
					seriesId: seriesId.value
				},
				success: (result) => {
					if (result.data.code == 200) {

						uni.downloadFile({
							url: `https://www.kaoyanzhengzhi.top/pdf/${userInfo._id}.pdf`,
							// url:`http://localhost/pdf/${userInfo._id}.pdf`,
							success: (res) => {
								if (res.statusCode === 200) {

									let filePath = res.tempFilePath;
									uni.openDocument({
										filePath,
										fileType: 'pdf',
										showMenu: true,
										success: function(file) {
											uni.hideLoading()

											// 去调取删除文件的接口
											uni.request({
												url: util.baseUrl +
													'/wxapi/wxQuestion/delateErrorPDF',
												method: 'post',
												data: {
													userId: userInfo._id,
												},
												success: () => {

												}
											})
										}
									});
								}

							},
							fail: (err) => {

							}


						})


					} else {
						uni.showToast({
							title: '还没有错题，请先刷题',
							icon: 'none'
						})
					}
				}
			})

		}
	}

	const redo = () => {
		uni.showModal({
			title: '提示',
			content: '确认要重新刷题吗？将会清空此系列的做题记录',
			success: function(res) {
				if (res.confirm) {
					totalNum.value = 0;
					correctNum.value = 0;
					doneNum.value = 0;
					const userInfo = uni.getStorageSync('userInfo')
					uni.request({
						url: util.baseUrl + `/wxapi/wxQuestion/redo`,
						method: 'POST',
						data: {
							seriesId: seriesId.value,
							userId: userInfo._id
						},
						success: () => {
							console.log('清除成功')
							getSection(seriesId.value);
						}
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	const adjustEchartData = (data) => {
		let names = []
		let rates = []
		data.forEach((item) => {
			names.push(item.label)
			let corrects = 0
			let dones = 0
			item.children.forEach((item2) => {
				corrects = corrects + item2.correct
				dones = dones + item2.done
			})
			console.log('corrects', corrects)
			console.log('dones', dones)
			// correctNum == 0 ? 0 : (correctNum * 100 / doneNum).toFixed(0)
			let rate = corrects == 0 ? 0 : (corrects * 100 / dones).toFixed(0)
			rates.push(rate)
		})
		const echartsData = {
			names,
			values: rates
		}
		optionBar.value = getOptionBar(echartsData)

	}
	// 模拟从接口获取echarts渲染的数据
	function getData() {
		setTimeout(() => {
			const data = {
				names: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
				values: [820, 932, 901, 934, 1290, 1330, 1320]
			}

			// optionLine.value = getOption(data)
			optionBar.value = getOptionBar(data)
			console.log(' optionBar.value', optionBar.value)

		}, 800)
	}

	function getOptionBar(datasource) {
		const {
			values,
			names
		} = datasource

		const option = {
			title: {
				text: '各部分正确率', // 主标题文本
				left: 'center', // 标题水平位置
				textStyle: { // 主标题样式
					color: '#000', // 文本颜色
					fontSize: 15 // 文本字号
				}
			},
			xAxis: {
				type: 'category',
				data: names,
				axisLabel: {
					interval: 0,
					rotate: 40,
				},
			},
			yAxis: {
				type: 'value'
			},
			series: [{
				data: values,
				type: 'bar',
				showBackground: true,
				label: {
					show: true,
					position: 'top'
				},

				backgroundStyle: {
					color: 'rgba(180, 180, 180, 0.2)'
				}
			}]
		}

		return option
	}
	const gorandom = () => {
		uni.request({
			url: util.baseUrl + '/wxapi/wxQuestion/randomQuestion',
			method: 'GET',
			data: {
				seriesId: seriesId.value
			},
			success: (res) => {
				if (res.data.code == 200) {
					const ids = {
						seriesId: seriesId.value,
						sectionId: sectionId.value,
						chapterId: "111",
						teacherId: teacherId.value

					}

					const idsStr = JSON.stringify(ids)

					const record = encodeURIComponent(JSON.stringify(res.data.data))
					uni.navigateTo({
						url: `/pages/questionList/questionList?record=${record}&ids=${idsStr}&from="random"`,
					})
				}
			}
		})
	}
	const goError = (item) => {
		console.log('item',item)
		const ids = {
			seriesId: seriesId.value,
			sectionId: item.id,
			chapterId: "111",
			teacherId: teacherId.value
		}
		
		const idsStr = JSON.stringify(ids)
		uni.navigateTo({
			url: `/pages/questionList/questionList?ids=${idsStr}&from=err`,
		})
	}
	const goErrorList = () => {
		infoPopup.value.open()
		return
		
		
		const userInfo = uni.getStorageSync('userInfo')
		uni.request({
			url: util.baseUrl + `/wxapi/wxQuestion/getErrorQuestionNew`,
			method: 'GET',
			data: {
				userId: userInfo._id,
				seriesId: seriesId.value
			},
			success: (res) => {
				if (res.data.data.questionArray.length) {
					let record = res.data.data.record
					// record.sort((a,b)=>{
					//   return a.store_check_id.length - b.store_check_id.length
					// })
					console.log('record',record)
					let questionArray = res.data.data.questionArray
					// questionArray.sort((a,b) => {
					// 	return a.type - b.type
					// })
					record.forEach((item1) => {
						questionArray.forEach((item2) => {
							if(item2 && item1) {  // 后端bug有些项返回为null  前端处理
								if (item1.questionId == item2._id && !item2.answered) {
								
									item2.store_check_id = item1.store_check_id
									item2.status = item1.status
									item2.collectStatus = item1.collectStatus
									item2.answered = item1.store_check_id.length > 0
									item2.options.forEach((item3) => {
										// 该选项是否在正确答案中
										if (item2.correct_id.includes(item3
												.select_id)) {
											item3.icon_url = true
											item3.iscorrect = true
										}
										// 该选项是否在选择的答案中
										if (item2.store_check_id.includes(item3
												.select_id)) {
											item3.whetherSubmit = true
										}
										// 如果该选项在选择的答案中且错误
										if (item2.store_check_id.includes(item3
												.select_id) && !item2
											.correct_id
											.includes(item3.select_id)) {
											item3.icon_url = false
											item3.iscorrect = false
										}
									})
								}
							}
							
						})
					})
					console.log('questionArrayquestionArray',questionArray)
					
					questionArray.sort((a,b) => {
						if(a.type > b.type) {
							return 1
						}else {
							return -1
						}
					})
					const idsStr = JSON.stringify(ids)
					// questionArray.splice(200, 100);
					const recordnew = encodeURIComponent(JSON.stringify(questionArray))
					// recordnew
					
				} 

			}
		})
	}
	const getSection = (id) => {
		uni.showLoading({
			title: '加载中'
		});
		const userInfo = uni.getStorageSync('userInfo')
		uni.request({
			url: util.baseUrl + `/wxapi/wxQuestion/getSection`,
			data: {
				seriesId: id,
				userId: userInfo._id
			},
			method: 'GET',
			success: (res) => {
				uni.hideLoading();

				tableList.value = res.data.data;
				// adjustEchartData(res.data.data)
				tableList.value.forEach((item1) => {

					item1.children.forEach((item2) => {
						totalNum.value = totalNum.value + item2.total
						doneNum.value = doneNum.value + item2.done
						correctNum.value = correctNum.value + item2.correct
						item1.total = item1.total + item2.total


					})
					item1.children.sort((a, b) => {
						if (a.creatTime > b.creatTime) {
							return 1
						} else {
							return -1
						}
					})

				})
			},
			fail: () => {

				uni.hideLoading();
			}
		})
	}
	const goQuestionList = (item) => {
		uni.showLoading({
			title: '加载中'
		});

		const userInfo = uni.getStorageSync('userInfo')
		// 获取做题记录
		uni.request({
			url: util.baseUrl + '/wxapi/wxQuestion/getQuestionByRecord',
			method: 'GET',
			data: {
				chapterId: item.id,
				userId: userInfo._id
			},
			success: (res) => {
				uni.hideLoading();
				if (res.data.code == 200) {
					// 获取该章的所有题
					uni.request({
						url: util.baseUrl + '/adminapi/question/list?chapterId=' + item.id,
						method: 'GET',
						success: (res2) => {

							let questionList = res2.data.data.result
							let record = res.data.data.record
							// 通过所有题目与答题记录进行匹配

							record.forEach((item1) => {
								questionList.forEach((item2) => {
									if (item1.questionId == item2
										._id) {

										item2.store_check_id = item1
											.store_check_id
										item2.status = item1.status
										item2.collectStatus = item1
											.collectStatus
										item2.answered = true
										item2.options.forEach((
											item3) => {
											// 该选项是否在正确答案中
											if (item2
												.correct_id
												.includes(item3
													.select_id)
											) {
												item3
													.icon_url =
													true
												item3
													.iscorrect =
													true
											}
											// 该选项是否在选择的答案中
											if (item2
												.store_check_id
												.includes(item3
													.select_id)
											) {
												item3
													.whetherSubmit =
													true
											}
											// 如果该选项在选择的答案中且错误
											if (item2
												.store_check_id
												.includes(item3
													.select_id
												) && !
												item2
												.correct_id
												.includes(item3
													.select_id)
											) {
												item3
													.icon_url =
													false
												item3
													.iscorrect =
													false
											}
										})
									}
								})
							})

							const ids = {
								seriesId: seriesId.value,
								sectionId: sectionId.value,
								chapterId: item.id,
								teacherId: teacherId.value

							}
							const idsStr = JSON.stringify(ids)
							const newrecord = encodeURIComponent(JSON.stringify(
								questionList))

							uni.navigateTo({
								url: `/pages/questionList/questionList?record=${newrecord}&ids=${idsStr}&lateDone=${item.lateDone}`,
							})
						}
					})


				}
			},
			fail: () => {
				uni.hideLoading();
			}
		})
		// console.log('item111',item)
		// const ids= {
		// 	seriesId:seriesId.value,
		// 	sectionId:sectionId.value,
		// 	chapterId:item.id,
		// 	teacherId:teacherId.value

		// }
		// console.log('22222222222ids',ids)
		// console.log('item.record',item.record)

	}
	const determin = (value) => {
		return value ? '../../static/put.png' : '../../static/retract.png'
	}
	const changeExpand = (index, value) => {
		tableList.value[index].expand = !value.expand;
		sectionId.value = value.id

	}
</script>

<style lang="scss">
	.uni-popup__wrapper {
		border-radius: 20rpx;
	}
	.infoPopup-content {
		position: relative;
		width: 500rpx;
		border-radius: 12rpx;
		padding: 24rpx;
		.item1 {
			margin: 30rpx 24rpx;
		}
		.section-name {
			font-weight: 700;
		}
	}
	.box {
		height: 500rpx;

		&+.box {
			margin-top: 30rpx;
		}
	}

	.contentList {
		height: 100vh;
		background-color: #fee793;

		.showType {
			display: flex;
			width: 400rpx;
			margin: 5rpx auto;
			justify-content: space-around;

			view {
				padding-bottom: 5px;
			}

			.selected {
				border-bottom: 2rpx solid #fcd22e;
			}
		}

		.top {
			position: fixed;
			height: 200rpx;
			width: 100%;
			font-weight: 700;
			background: linear-gradient(to bottom, #fcd22e, #fee793);
			display: flex;

			.top-img {
				margin-left: 60rpx;
				width: 190rpx;
				height: 134rpx;
				background: url(https://pic.imgdb.cn/item/6691f34ad9c307b7e9a6ac51.png);
				background-size: 100% 100%;
			}

			.top-text {
				margin-top: 50rpx;
				width: 390rpx;
				height: 40rpx;
				background: url(https://pic.imgdb.cn/item/6691f692d9c307b7e9aa3711.png);
				background-size: 100% 100%;
			}
		}

		.body-top {
			// font-size: 28rpx;
			display: flex;
			justify-content: space-evenly;
			position: absolute;
			z-index: 10;
			left: 50%;
			transform: translateX(-50%);
			height: 100rpx;
			background: linear-gradient(to bottom, #fbf7d8, #fff);
			width: 600rpx;
			top: 130rpx;
			padding: 0rpx 20rpx;
			padding-top: 30rpx;
			border-radius: 20rpx;
			box-shadow: 2rpx 2rpx 2rpx 2rpx #fdfcf9;

			.bookName {
				position: absolute;
				left: 120rpx;
				top: 20rpx;
				font-weight: 700;
			}

			.count {
				position: absolute;
				left: 120rpx;
				top: 70rpx;
				font-size: 26rpx;
				color: #9f9f9f;

			}

			.rate {
				position: absolute;
				right: 30rpx;
				top: 20rpx;

				.rate-num {
					color: #be1d1f;
					font-weight: 700;
				}

				.rate-text {
					font-size: 26rpx;
					color: #fcd22e;
				}
			}

			.img {
				position: absolute;
				left: 20rpx;
				top: 20rpx;
				width: 80rpx;
				height: 80rpx;

				image {
					width: 100%;
					height: 100%;
				}

			}
		}

		.body {
			background-color: #f8f8f8;
			position: absolute;
			height: calc(100vh - 200rpx);

			top: 200rpx;
			width: 100%;
			background-color: #f7f7f9;
			border-top-left-radius: 40rpx;
			border-top-right-radius: 40rpx;

			.body-title {
				font-size: 28rpx;
				text-align: center;
				background-color: #fff;
				display: flex;
				justify-content: space-around;
				align-items: center;
				height: 300rpx;
				border-bottom: 2rpx solid #e4e2e0;
				padding-top: 60rpx;
				// background: url(../../static/booktop.png) no-repeat;
				// background-size: 100% 100%;
				//width: 640rpx;
				border-top-left-radius: 40rpx;
				border-top-right-radius: 40rpx;

				.text {
					width: 100%;
					position: absolute;
					left: 50%;
					transform: translateX(-50%);
					bottom: -80rpx;
				}

				.left,
				.right {
					position: relative;
					width: 120rpx;
					height: 120rpx;
					border-radius: 60rpx;

					.img {
						position: absolute;
						left: 50%;
						top: 50%;
						transform: translate(-50%, -50%);
						width: 90rpx;
						height: 90rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}

				}

				.left {
					background: linear-gradient(to right, #e1392d, #d19a66);
				}

				.middle,
				.error {
					position: relative;

					width: 120rpx;
					height: 120rpx;
					border-radius: 60rpx;
					background: linear-gradient(to right, #fbc118, #f1dda4);

					// .text {
					// 	bottom: -50rpx;
					// }

					.img {
						position: absolute;
						left: 50%;
						top: 50%;
						transform: translate(-50%, -50%);
						width: 90rpx;
						height: 90rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}
				}

				.error {
					background: linear-gradient(to right, #5090f9, #16ddeb);
				}

				.right {
					background: linear-gradient(to right, #1ba035, #39e274);
				}
			}

			.section {

				.item1 {
					position: relative;
					background-color: #fff;

					width: 560rpx;
					margin: 10rpx auto;
					padding: 20rpx 50rpx;
					border-radius: 10rpx;

				}

				.item2-box {
					margin-top: 40rpx;
				}

				.item2 {
					display: flex;
					justify-content: space-between;
					position: relative;
					margin-bottom: 30rpx;

					.chapterName {
						color: #626262;
					}

					.rate {
						color: #9f9f9f;
						font-size: 26rpx;
						margin-right: 30rpx;
					}

					.item2-icon {
						position: absolute;
						top: 2rpx;
						right: 0rpx;
						width: 25rpx;
						height: 25rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}
				}

				.title {
					display: flex;
					justify-content: space-between;

					.schedule {
						color: #626262;
						font-size: 28rpx;
					}
				}

				.section-name {
					font-weight: 700;
				}

				.section-icon {
					left: 10rpx;
					position: absolute;
					width: 30rpx;
					height: 30rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}

		}
	}
</style>